﻿using System;
using Ymatou.User.Dto;
using Ymatou.User.Dto.Auth;
using Ymatou.User.Dto.PasswordAction;
using YmtAuth.Domain.Model.LoginAuth;
using YmtAuth.Domain.Repository;
using YmtAuth.Dto;
using YmtSystem.CrossCutting;

namespace YmtAuth.AppService
{

    public class PasswordAppService : IPasswordAppService
    {
        private IUserLoginBillsRepository UlcRepo { get { return LocalServiceLocator.GetService<IUserLoginBillsRepository>(); } }

        private ITokenAppService TokenAppService { get { return LocalServiceLocator.GetService<ITokenAppService>(); } }

        public bool TradingPasswordEqualsLoginPassword(string tradingPassword, int userId)
        {
            var userLc = UlcRepo.FindOne(UserLoginAuthSpecifications.MatchLoginUserId(userId));
            if (userLc == null) return false;
            return userLc.CheckTradingPasswordEqualsLoginPassword(tradingPassword);
        }

        public ResponseData<ResetPasswordReponseCode> ChangUserPasswordById(PasswordRequestDto dto)
        {
            
            YmtSystemAssert.AssertArgumentNotNull(dto, "PasswordRequestDto 不能为空");
            YmatouLoggingService.Debug("修改密码；PasswordRequestDto, UserId：{0}，修改密码依据：{1}", dto.UserId, dto.AType);

            if (string.IsNullOrEmpty(dto.NewPassword)) return ResponseData<ResetPasswordReponseCode>.CreateFail(ResetPasswordReponseCode.NewPasswordEmpty, lastErrorMessage: "密码不能为空");
            if (dto.AType == ActionType.Other) return ResponseData<ResetPasswordReponseCode>.CreateFail(ResetPasswordReponseCode.DtoError, lastErrorMessage: "错误的 ActionType");
            UserLoginBill ulc = null;
            if (dto.AType == ActionType.ByUserId)
                ulc = UlcRepo.FindOne(UserLoginAuthSpecifications.MatchLoginUserId(dto.UserId));
            else if (dto.AType == ActionType.ByMobile)
                ulc = UlcRepo.FindOne(UserLoginAuthSpecifications.MatchLoginMobile(dto.LoginMobile));
            //else if (dto.AType == ActionType.ByMail)
            //    ulc = UlcRepo.FindOne(UserLoginAuthSpecifications.WatchLoginMail(dto.LoginMail));

            if (ulc == null)
            {
                YmatouLoggingService.Debug("用户不存在: {0}", dto.UserId);
                return ResponseData<ResetPasswordReponseCode>.CreateFail(ResetPasswordReponseCode.UserNotFind, lastErrorMessage: "用户不存在");
            }

            var result = ulc.ChangPassword(dto.NewPassword, dto.PasActionType, dto.OldPassword);
            if (result != ResetPasswordReponseCode.Success)
            {
                YmatouLoggingService.Debug("用户 {0} 设置密码失败，原因,{1}", ulc.LoginBills.LoginId, result.GetDescription());
                                                          
                return ResponseData<ResetPasswordReponseCode>.CreateFail(result,errorCode:((int)result).ToString()
                    ,lastErrorMessage: result.GetDescription("设置密码错误"));
            }
            UlcRepo.Save(ulc);

            if (dto.PasActionType == PasswordActionType.ModifyLoginPassword)
            {
                YmatouLoggingService.Debug("ChangUserPasswordById；RemoveToken, UserId: {0}, Token: {1}", ulc.UserId, ulc.Token);
                //移除token
                TokenAppService.RemoveToken(new UserRemoveTokenRequestDto() { UserId = ulc.UserId });
            }
            return ResponseData<ResetPasswordReponseCode>.CreateSuccess(ResetPasswordReponseCode.Success, "ok");
        }
    }
}
